package com.uxwine.widget;

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;

public class MenuWindow extends ActionWindow implements View.OnKeyListener
{

	protected ListView mMenu;
	
	public MenuWindow(Context ctx)
	{
		super(ctx);
		initView();
	}
	
	public MenuWindow(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		initView();
	}

	private void initView()
	{
		final Context ctx = getContext();
		final Resources res = ctx.getResources();
		final String pkg = ctx.getPackageName();
		final int resId = res.getIdentifier("view_menu", "layout", pkg);
		final int listId = res.getIdentifier("menu_list", "id", pkg);
		
		setContentView(resId);
		View v = getContentView();
		v.setFocusable(true);
		v.setOnKeyListener(this);
		v.setFocusableInTouchMode(true);
		mMenu = (ListView)v.findViewById(listId);
		mMenu.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				exit(position);
			}
		});
	}
	
	public void setAdapter(ListAdapter adapter)
	{
		mMenu.setAdapter(adapter);
	}

	public void show(View anchor)
	{
		showAsDropDown(anchor, anchor.getWidth(), 0);
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event)
	{
		if (isShowing())
		{
			dismiss();
		}
		return false;
	}
}
